<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据日期" prop="riqi">
        <el-date-picker clearable v-model="queryParams.riqi" type="date" value-format="YYYY-MM-DD" placeholder="日期大于等于">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单据日期" prop="riqi2">
        <el-date-picker clearable v-model="queryParams.riqi2" type="date" value-format="YYYY-MM-DD"
          placeholder="日期小于等于">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单号" prop="danhao">
        <el-input v-model="queryParams.danhao" placeholder="请输入单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="结算方式" prop="jiesuanfangshi">
        <el-select v-model="queryParams.jiesuanfangshi" placeholder="请选择结算方式" clearable>
          <el-option v-for="dict in settlement_method" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="beizhu">
        <el-input v-model="queryParams.beizhu" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="单据分类" prop="nrtype">
        <el-select v-model="queryParams.nrtype" placeholder="请选择单据分类" clearable>
          <el-option v-for="dict in repairtype" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否结算" prop="isjiesuan">
        <el-select v-model="queryParams.isjiesuan" placeholder="请选择是否结算" clearable>
          <el-option v-for="dict in is_settlement" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="beizhu">
        <el-input v-model="queryParams.kname" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车牌号" prop="beizhu">
        <el-input v-model="queryParams.carno" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车型" prop="beizhu">
        <el-input v-model="queryParams.chexing" placeholder="请输入车型" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车架号" prop="beizhu">
        <el-input v-model="queryParams.chejiahao" placeholder="请输入车架号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="保险公司" prop="beizhu">
        <el-input v-model="queryParams.bxgsName" placeholder="请输入保险公司" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['carrepair:wxdnr:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['carrepair:wxdnr:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['carrepair:wxdnr:remove']">删除</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['carrepair:wxdnr:export']"
          >导出</el-button
        >
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handlePrint">打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleAudit">审核</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="wxdnrTable" v-loading="loading" :data="wxdnrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据日期" align="center" prop="riqi" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.riqi, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单号" align="center" prop="danhao" />
      <el-table-column label="车辆/客户信息" width="300" align="center" prop="zhCar" />
      <el-table-column label="车牌号" align="center" prop="carno" />
      <el-table-column label="是否结算" align="center" prop="isjiesuan">
        <template #default="scope">
          <dict-tag :options="is_settlement" :value="scope.row.isjiesuan" />
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="zsum" />
      <el-table-column label="公里数" align="center" prop="gonglishu" />
      <el-table-column label="保险公司" align="center" prop="bxgsName" />
      <el-table-column label="保险到期日期" align="center" prop="baoxiandqrq" />
      <el-table-column label="备注" align="center" prop="beizhu" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['carrepair:wxdnr:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['carrepair:wxdnr:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <div style="
        background-color: #ccc;
        margin-top: 25px;
        padding: 5px;
        display: flex;
      ">
      <div style="text-indent: 25px">配件销售金额:{{ sumData.peijianSum }}</div>
      <div style="text-indent: 25px">维修总金额:{{ sumData.weixiuSum }}</div>
      <div style="text-indent: 25px">总金额：{{ sumData.zSum }}</div>
    </div>

    <!-- 添加或修改维修单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="90%" append-to-body>
      <el-form ref="wxdnrRef" :model="form" :rules="rules" label-width="80px"
        style="height: 70vh; overflow-y: auto; overflow-x: hidden">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据日期" prop="riqi">
              <el-date-picker clearable v-model="form.riqi" type="date" value-format="YYYY-MM-DD" placeholder="请选择单据日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单号" prop="danhao">
              <el-input v-model="form.danhao" placeholder="请输入单号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据分类" prop="nrtype">
              <el-select v-model="form.nrtype" placeholder="请选择单据分类">
                <el-option v-for="dict in repairtype" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="结算方式" prop="jiesuanfangshi">
              <el-select v-model="form.jiesuanfangshi" placeholder="请选择结算方式">
                <el-option v-for="dict in settlement_method" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公里数" prop="gonglishu">
              <el-input v-model="form.gonglishu" placeholder="请输入公里数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="beizhu">
              <el-input v-model="form.beizhu" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="车辆信息" prop="zhCar">
              <el-input v-model="form.zhCar" placeholder="请输入车辆信息编号" readonly style="width: calc(100% - 80px)" />
              <el-button type="primary" style="width: 80px" @click="checkCar">选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-tabs v-model="activeName">
          <!-- 选项卡1、配件明细 -->
          <el-tab-pane label="配件明细" name="first">
            <div style="height: 40px; background-color: #f1f1f1">
              <el-button type="primary" @click="selectPeijian">新增1</el-button>
              <el-button type="primary" @click="addpjbt">新增2</el-button>
              <el-button type="danger" @click="delpjmx">删除</el-button>
            </div>
            <div>
              <el-table ref="pjmxTable" :data="pjmxList" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="pjpid" label="配件编号" width="250">
                </el-table-column>
                <el-table-column prop="pname" label="配件名称" width="250">
                </el-table-column>
                <el-table-column prop="chexing" label="车型" width="180">
                </el-table-column>
                <el-table-column prop="shuliang" label="数量" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.shuliang" size="small" oninput="value=value.replace(/[^0-9.]/g,'')"
                      @change="txtChange"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="danjia" label="单价" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.danjia" size="small" oninput="value=value.replace(/[^0-9.]/g,'')"
                      @change="txtChange"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="jine" label="金额" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.jine" size="small" readonly="readonly"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="beizhu" label="备注">
                  <template #default="scope">
                    <el-input v-model="scope.row.beizhu" size="small"></el-input>
                  </template>
                </el-table-column>
              </el-table>

              <div>配件总金额：{{ pjJine }}</div>
            </div>
          </el-tab-pane>
          <!-- 选项卡2、维修项目明细 -->
          <el-tab-pane label="维修项目明细" name="second">
            <div style="height: 40px; background-color: #f1f1f1">
              <el-button type="primary" @click="wxmxAddBt">新增</el-button>
              <el-button type="danger" @click="delpjwx">删除</el-button>
            </div>
            <div>
              <el-table ref="wxmxTable" :data="wxmxList" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="weixiuxiangmu" label="维修项目" width="300">
                  <template #default="scope">
                    <el-input v-model="scope.row.weixiuxiangmu" size="small"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="jine" label="费用" width="180">
                  <template #default="scope">
                    <el-input v-model="scope.row.jine" size="small"
                      oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="beizhu" label="备注">
                  <template #default="scope">
                    <el-input v-model="scope.row.beizhu" size="small"></el-input>
                  </template>
                </el-table-column>
              </el-table>
              <div>维修总金额：{{ wxzJine }}</div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div style="
            background-color: #ccc;
            margin-top: 10px;
            text-align: right;
            padding-right: 20px;
            height: 30px;
            line-height: 30px;
            margin-bottom: 30px;
          ">
          合计总金额：{{ zongJine }}
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailSave">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="车辆信息选择" v-model="openCar" width="90%" append-to-body>
      <car :isSelect="true" @checkRow="setCar" @closeWin="closeWin" />
    </el-dialog>

    <el-dialog title="配件选择" v-model="openPj" width="90%" append-to-body>
      <peijian ref="peijianModel" :isSelect="true" @checkRow="setPj" @multipleCheck="msetPj" @closeWin="closeWin" />
    </el-dialog>

    <el-dialog title="配件添加" v-model="dialogVisible_pj2add" width="500">
      <div style="height: 200px; overflow-y: auto; overflow-x: hidden">
        <el-form label-width="120px" :model="pjmxInput">
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="配件编号">
                <el-input v-model="pjmxInput.mxpjid"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="配件名称">
                <el-input v-model="pjmxInput.mxpname"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="车型">
                <el-input v-model="pjmxInput.mxchexing"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="销售价">
                <el-input v-model="pjmxInput.mxxiaoshoujia" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_pj2add = false">取 消</el-button>
        <el-button type="primary" @click="pj2addconfirm">确 认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="维修项目设置" v-model="dialogVisible_Wxmx" width="500">
      <div style="height: 200px; overflow-y: auto; overflow-x: hidden">
        <el-form label-width="120px" :model="wxmxInput">
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="维修项目">
                <el-input v-model="wxmxInput.weixiuxiangmu"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
            <el-col :span="20">
              <el-form-item label="费用">
                <el-input v-model="wxmxInput.jine" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_Wxmx = false">取 消</el-button>
        <el-button type="primary" @click="wxmxSelect">确 认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="单据打印" v-model="dialogVisible_print" width="90%">
      <div style="height: 70vh; overflow-y: auto; overflow-x: hidden">
        <div id="printTable">
          <div style="text-align: center; font-size: 22px; font-weight: bold">
            {{ deptInfo.printTitle }}
          </div>
          <div style="margin-top: 10px">
            <table style="width: 98%; margin: 0 auto">
              <tr>
                <td style="width: 33.33%">
                  单据日期：{{ moment(form.riqi).format("YYYY-MM-DD") }}
                </td>
                <td style="width: 33.33%">单号：{{ form.danhao }}</td>
                <td style="width: 33.33%">车牌号：{{ form.carno }}</td>
              </tr>
              <tr>
                <td style="width: 33.33%">客户名称：{{ form.kname }}</td>
                <td style="width: 33.33%">联系电话：{{ form.dianhua }}</td>
                <td style="width: 33.33%">
                  结算方式：{{ form.jiesuanfangshi == 1 ? "挂账" : "现金" }}
                </td>
              </tr>
              <tr>
                <td style="width: 33.33%">车型：{{ form.chexing }}</td>
                <td style="width: 33.33%">里程数：{{ form.gonglishu }}</td>
                <td style="width: 33.33%"></td>
              </tr>
            </table>
          </div>
          <div style="margin-top: 10px" v-if="pjmxList.length > 0">
            配件明细
            <table style="width: 100%; margin: 0 auto" class="fine-line-table">
              <tr style="text-align: center; font-weight: bold">
                <td style="width: 70px">序号</td>
                <td style="width: 90px; text-align: left">配件编号</td>
                <td>配件名称</td>
                <td>车型</td>
                <td style="width: 70px">数量</td>
                <td style="width: 90px">单价</td>
                <td style="width: 90px">金额</td>
              </tr>
              <tr v-for="(item, index) in pjmxList" :key="index">
                <td style="text-align: center">{{ index + 1 }}</td>
                <td>{{ item.pjpid }}</td>
                <td>{{ item.pname }}</td>
                <td>{{ item.chexing }}</td>
                <td>{{ item.shuliang }}</td>
                <td>{{ item.danjia }}</td>
                <td>{{ item.jine }}</td>
              </tr>
              <tr>
                <td colspan="7">配件合计：{{ form.peijiansum }}</td>
              </tr>
            </table>
          </div>
          <div style="margin-top: 10px" v-if="wxmxList.length > 0">
            维修项目
            <table style="width: 100%; margin: 0 auto" class="fine-line-table">
              <tr v-for="(item, index) in wxmxList" :key="index">
                <td style="width: 70px; text-align: center">{{ index + 1 }}</td>
                <td style="width: 200px">{{ item.weixiuxiangmu }}</td>
                <td>{{ item.jine }}</td>
              </tr>
              <tr>
                <td colspan="3">维修合计：{{ form.weixiusum }}</td>
              </tr>
            </table>
          </div>
          <div style="text-align: right; margin-right: 50px">
            总费用：{{ form.zsum }}
          </div>
          <div>{{ deptInfo.printContent }}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-print="'#printTable'">打 印</el-button>
        <el-button @click="dialogVisible_print = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup name="Wxdnr">
import router from "@/router";
import moment from "moment";
import {
  sumWxdnr,
  listWxdnr,
  getWxdnr,
  delWxdnr,
  addWxdnr,
  updateWxdnr,
  audit
} from "@/api/carrepair/wxdnr";
import { getDeptInfo } from "@/api/system/dept";

import { listPeijianmxNoPage } from "@/api/carrepair/peijianmx";
import { listWeixiumxNoPage } from "@/api/carrepair/weixiumx";

import car from "@/views/carrepair/car/index";
import peijian from "@/views/carrepair/peijian/index";
import { reactive, ref, computed, toRaw } from "vue";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const { is_settlement, settlement_method, repairtype } = proxy.useDict(
  "is_settlement",
  "settlement_method",
  "repairtype"
);
//console.log('is_settlement',is_settlement);

const wxdnrList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let openPj = ref(false);
let dialogVisible_print = ref(false);
let wxdnrTable = ref(null);
let deptInfo = ref({});

const closeWin = (url) => {
  openCar.value = false;
  openPj.value = false;
  open.value = false;
  router.push(url);
};
const handlePrint = () => {
  pjmxList.splice(0);
  wxmxList.splice(0);
  var rows = wxdnrTable.value.getSelectionRows();
  if (rows.length == 0) {
    ElMessage.error("请选择要打印的数据！勾选左侧选项。");
    return;
  }
  getDeptInfo().then((res) => {
    console.log("printRes", res);
    Object.assign(deptInfo.value, res.data);
    handleUpdate(rows[0], "维修单打印");
    dialogVisible_print.value = true;
  });
};

let yue = '01';
if (new Date().getMonth() + 1 < 10) {
  yue = '0' + (new Date().getMonth() + 1);
} else {
  yue = (new Date().getMonth() + 1) + '';
}
let jintian =
  new Date().getFullYear() + "-" + yue + "-01";
console.log("jintian", jintian);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    riqi: jintian,
    danhao: null,
    jiesuanfangshi: null,
    beizhu: null,
    nrtype: null,
    isjiesuan: "1",
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

let peijianModel = ref(null);

let wxmxList = reactive([]);
let pjmxList = reactive([]);

//维修项目明细删除
let wxmxTable = ref(null);
const delpjwx = () => {
  let newdata = wxmxList.filter((row) => {
    return !wxmxTable.value.getSelectionRows().includes(row);
  });
  wxmxList.splice(0, wxmxList.length);
  wxmxList.push(...newdata);
};

//配件明细的删除
let pjmxTable = ref(null);
const delpjmx = () => {
  let newdata = pjmxList.filter((row) => {
    return !pjmxTable.value.getSelectionRows().includes(row);
  });

  pjmxList.splice(0, pjmxList.length);
  pjmxList.push(...newdata);
};

//======维修明细模块处理=======//
const dialogVisible_Wxmx = ref(false);
const wxmxInput = reactive({
  weixiuxiangmu: null,
  jine: null,
});
//弹出框确认
const wxmxSelect = () => {
  if (wxmxInput.weixiuxiangmu == null) {
    ElMessage({
      message: "操作失败，维修项目不能为空！",
      type: "error",
    });
    return;
  }
  const item = {
    id: null,
    weixiuxiangmu: wxmxInput.weixiuxiangmu,
    jine: wxmxInput.jine,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: null,
  };

  wxmxList.push(item);

  dialogVisible_Wxmx.value = false;
  //alert(JSON.stringify(wxmxInput))
};
//维修明细“新增”按钮点击
const wxmxAddBt = () => {
  wxmxInput.weixiuxiangmu = null;
  wxmxInput.jine = null;
  dialogVisible_Wxmx.value = true;
};
//======维修明细模块处理结束=======//

//配件明细添加
let dialogVisible_pj2add = ref(false);
let pjmxInput = reactive({
  mxpname: null,
  mxchexing: null,
  mxpjid: null,
  mxxiaoshoujia: null,
});
const addpjbt = () => {
  dialogVisible_pj2add.value = true;
};

const pj2addconfirm = () => {
  if (pjmxInput.mxpname == null) {
    ElMessage({
      message: "配件名称不能为空！",
      type: "error",
    });
    return;
  }
  let item = {
    id: null,
    pid: null,
    pname: pjmxInput.mxpname,
    chexing: pjmxInput.mxchexing,
    pjpid: pjmxInput.mxpjid,
    shuliang: 1,
    danjia: pjmxInput.mxxiaoshoujia,
    jine: pjmxInput.mxxiaoshoujia == null ? 0 : pjmxInput.mxxiaoshoujia,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: null,
    mxpname: pjmxInput.mxpname,
    mxchexing: pjmxInput.mxchexing,
    mxpjid: pjmxInput.mxpjid,
    notselectdata: 1,
  };
  pjmxList.push(item);
  pjmxInput.mxpname = null;
  pjmxInput.mxchexing = null;
  pjmxInput.mxpjid = null;
  pjmxInput.mxxiaoshoujia = null;
  dialogVisible_pj2add.value = false;
};

//公共调用方法，在多选和单选之后的共同操作
const sameSelectMethed = () => {
  //重新计算每列金额
  txtChange();
  peijianModel.value.clearSelectRow();
  openPj.value = false;
};
//这是商品页面 》 商品列表页面点击【选择】按钮时调用的、这里是单选
const tbSelectbt = (x) => {
  //alert(JSON.stringify(x));
  var rowItem = {
    id: null,
    pid: x.id,
    pname: x.pname,
    chexing: x.chexing,
    pjpid: x.pid,
    shuliang: 1,
    danjia: x.xiaoshoujia,
    jine: 0,
    beizhu: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    nrId: null,
  };
  pjmxList.push(rowItem);
  sameSelectMethed();
};

const selectPeijian = () => {
  openPj.value = true;
};

const setPj = (obj) => {
  console.log("pjObj", obj);
  tbSelectbt(obj);
};

const msetPj = (objs) => {
  for (var i = 0; i < objs.length; i++) {
    tbSelectbt(objs[i]);
  }
};

const txtChange = () => {
  for (var i = 0; i < pjmxList.length; i++) {
    pjmxList[i].jine = pjmxList[i].shuliang * pjmxList[i].danjia;
  }
};

//配件总金额
const pjJine = computed({
  get() {
    let zjine = 0;
    for (var i = 0; i < pjmxList.length; i++) {
      if (pjmxList[i].jine != null) {
        zjine = zjine + parseFloat(pjmxList[i].jine);
      }
    }
    return zjine;
  },
  set(newVal) {
    console.log(newVal); // 李-四
  },
});

//维修总金额
const wxzJine = computed({
  // 读取值
  get() {
    let zjine = 0;
    for (var i = 0; i < wxmxList.length; i++) {
      if (wxmxList[i].jine != null) {
        zjine = zjine + parseFloat(wxmxList[i].jine);
      }
    }
    return zjine;
  },
  // 写入值
  set(newVal) {
    console.log(newVal); // 李-四
    //[firstName.value, lastName.value] = newVal.split('-') // 解构赋值
  },
});

const zongJine = computed({
  // 读取值
  get() {
    let zjine = 0;
    for (var i = 0; i < pjmxList.length; i++) {
      if (pjmxList[i].jine != null) {
        zjine = zjine + parseFloat(pjmxList[i].jine);
      }
    }
    for (var i = 0; i < wxmxList.length; i++) {
      if (wxmxList[i].jine != null) {
        zjine = zjine + parseFloat(wxmxList[i].jine);
      }
    }
    return zjine;
  },
  // 写入值
  set(newVal) {
    console.log(newVal); // 李-四
    //[firstName.value, lastName.value] = newVal.split('-') // 解构赋值
  },
});

//选项卡默认选择项
const activeName = ref("first");

let openCar = ref(false);

const checkCar = () => {
  openCar.value = true;
};

const setCar = (obj) => {
  data.form.zhCar =
    "客户名称：" +
    obj.kname +
    "、电话：" +
    obj.dianhua +
    "、车牌号：" +
    obj.carno +
    "、车型：" +
    obj.chexing +
    "、车架号：" +
    obj.chejiahao +
    "、保险公司名称：" +
    obj.bxgsName +
    "、保险到期日期：" +
    obj.baoxiandqrq;
  data.form.carId = obj.id;
  openCar.value = false;
};

/** 查询维修单管理列表 */
let sumData = ref({ peijianSum: 0, weixiuSum: 0, zSum: 0 });
function getList() {
  loading.value = true;
  console.log("queryParams.value", queryParams.value);
  listWxdnr(queryParams.value).then((response) => {
    let list = response.rows;
    for (var i = 0; i < list.length; i++) {
      Object.assign(list[i], {
        zhCar:
          "客户名称：" +
          list[i].kname +
          "、电话：" +
          list[i].dianhua +
          "、车型：" +
          list[i].chexing +
          "、车架号：" +
          list[i].chejiahao
      });
    }
    wxdnrList.value = list;
    total.value = response.total;
    loading.value = false;
  });
  sumWxdnr(queryParams.value).then((res) => {
    console.log("sumRes", res);
    sumData.value.peijianSum = res.peijianSum;
    sumData.value.weixiuSum = res.weixiuSum;
    sumData.value.zSum = res = res.zSum;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    riqi: null,
    danhao: null,
    carId: null,
    jiesuanfangshi: null,
    gonglishu: null,
    peijiansum: null,
    weixiusum: null,
    zsum: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    IsDeleted: null,
    beizhu: null,
    RowVersion: null,
    notselectdataCar: null,
    nrtype: null,
    isjiesuan: null,
    toApplet: null,
  };
  proxy.resetForm("wxdnrRef");
}

//明细保存
const detailSave = async () => {
  if (data.form.riqi == null) {
    ElMessage.error("保存失败，日期信息尚未设置！");
    return;
  }

  if (data.form.carId == null) {
    ElMessage.error("保存失败，车辆、用户信息尚未设置！");
    return;
  }
  data.form.peijiansum = pjJine.value;
  data.form.weixiusum = wxzJine.value;
  data.form.zsum = zongJine.value;
  let subData = {
    nr: JSON.stringify(toRaw(data.form)),
    listPeijian: JSON.stringify(toRaw(pjmxList)),
    listWeixiu: JSON.stringify(toRaw(wxmxList)),
  };
  console.log("subData", subData);
  if (form.value.id != null) {
    updateWxdnr(subData).then((res) => {
      //console.log('updres',res);
      if (res.code == 200) {
        ElMessage.success("维修单数据保存成功！");
        pjmxList.splice(0, pjmxList.length);
        wxmxList.splice(0, wxmxList.length);
        let row = data.form;
        row.id = res.data.returnId;
        handleUpdate(row);
      }
    });
  } else {
    addWxdnr(subData).then((res) => {
      ElMessage.success("维修单数据保存成功！");
      console.log("addRes", res);
      pjmxList.splice(0, pjmxList.length);
      wxmxList.splice(0, wxmxList.length);
      reset();
      open.value = false;
      handleQuery();
    });
  }
  /*
  if (res.Tag == 1) {
    ElMessage({
      message: '操作成功！',
      type: 'success'
    })
    mx.value.dialogVisible = false
    await reloadPagerData(Pagination)
  } else {
    ElMessage({
      message: res.Message,
      type: 'error'
    })
  }
  */
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  var today = new Date();

  // 获取今天的日期
  var year = today.getFullYear(); // 获取年份
  var month = today.getMonth() + 1; // 获取月份，+1因为getMonth返回的月份从0开始
  var day = today.getDate(); // 获取日
  // 如果需要格式化为YYYY-MM-DD字符串
  var jintian = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);

  console.log('jintian2', jintian);
  data.form.riqi = jintian;
  pjmxList.splice(0, pjmxList.length);
  wxmxList.splice(0, wxmxList.length);
  open.value = true;
  title.value = "添加维修单管理";
}

/** 修改按钮操作 */
function handleUpdate(row, leixing) {
  reset();
  const _id = row.id || ids.value;
  //获取维修单详情
  getWxdnr(_id).then((response) => {
    let obj = {
      zhCar:
        "客户名称：" +
        response.data.kname +
        "、电话：" +
        response.data.dianhua +
        "、车牌号：" +
        response.data.carno +
        "、车型：" +
        response.data.chexing +
        "、车架号：" +
        response.data.chejiahao +
        "、保险公司名称：" +
        response.data.bxgsName +
        "、保险到期日期：" +
        response.data.baoxiandqrq,
    };
    Object.assign(response.data, obj);

    form.value = response.data;
    if (leixing == "维修单打印") {
    } else {
      open.value = true;
      title.value = "修改维修单管理";
    }

    //获取配件明细列表
    pjmxList.splice(0, pjmxList.length);
    listPeijianmxNoPage({ nrId: row.id || ids.value[0] }).then((res) => {
      //console.log("mxRes", res);
      pjmxList.push(...res);
    });

    wxmxList.splice(0, wxmxList.length);
    //获取维修明细列表
    listWeixiumxNoPage({ nrId: row.id || ids.value[0] }).then((res) => {
      console.log("wxRes", res);
      wxmxList.push(...res);
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["wxdnrRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateWxdnr(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWxdnr(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除维修单管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delWxdnr(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 删除按钮操作 */
function handleAudit(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认审核维修单管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return audit(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("审核成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "carrepair/wxdnr/export",
    {
      ...queryParams.value,
    },
    `wxdnr_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
.fine-line-table {
  border-collapse: collapse;
  width: 100%;
}

.fine-line-table,
.fine-line-table th,
.fine-line-table td {
  border: 1px solid #ddd;
}

.disableInput {
  border: 1px solid #2d2d2d;
  width: calc(100% - 85px);
  height: 30px;
  line-height: 30px;
  margin-right: 5px;
  background-color: #e5e5e5;
}
</style>
